package com.five.core.filter;



import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class CharacterEncodingFilter implements Filter {


    //获取配置的编码
    private String encoding;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        encoding = filterConfig.getInitParameter("encoding");
        if(encoding==null||encoding.trim().equals("")){
            encoding="UTF-8";
        }

    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {

        //1.向下转型
        HttpServletRequest request= (HttpServletRequest) req;
        HttpServletResponse response= (HttpServletResponse) res;

        //解决请求的post乱码
        request.setCharacterEncoding(encoding);

        //解决响应乱码
        response.setCharacterEncoding(encoding);
        response.setContentType("application/json;charset="+encoding);

        //放行
        chain.doFilter(request,response);


    }

    @Override
    public void destroy() {

    }
}